<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="offer_id" prop="offerId">
        <el-input
          v-model="queryParams.offerId"
          placeholder="请输入offer_id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="price" prop="price">
        <el-input
          v-model="queryParams.price"
          placeholder="请输入price"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="quantity" prop="quantity">
        <el-input
          v-model="queryParams.quantity"
          placeholder="请输入quantity"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="offer_name" prop="offerName" label-width="100px">
        <el-input
          v-model="queryParams.offerName"
          placeholder="请输入offer_name"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['purchase:offers:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['purchase:offers:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="offersList" @selection-change="handleSelectionChange" @sort-change="handleSortChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="offer_id" align="center" prop="offerId" />
      <el-table-column label="offer_name" align="center" prop="offerName">
        <template slot-scope="scope">
          <div style="white-space: pre-line; text-align: left;">
            {{ scope.row.offerName }}
          </div>
        </template>
      </el-table-column>

      <el-table-column label="price" align="center" prop="price" sortable="custom" />
      <el-table-column label="quantity" align="center" prop="quantity" sortable="custom">
        <template slot="header">
          <el-tooltip :content="'total: ' + quantityTotal" placement="top">
            <span>quantity</span>
          </el-tooltip>
        </template>
      </el-table-column>

      <el-table-column label="bonus" align="center" prop="bonus" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['purchase:offers:edit']"
          >修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 修改offers对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- 添加 inventory 选择下拉框 -->
        <el-form-item label="Product" prop="productId">
          <el-select
            v-model="form.productId"
            placeholder="请选择product"
            style="width: 100%"
            @change="handleInventoryChange"
            disabled>
            <el-option
              v-for="item in inventoryList"
              :key="item.productId"
              :label="item.name"
              :value="item.productId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="price" prop="price">
          <el-input v-model="form.price" placeholder="请输入price" />
        </el-form-item>
        <el-form-item label="quantity" prop="quantity">
          <el-input v-model="form.quantity" placeholder="请输入quantity" />
        </el-form-item>
        <el-form-item label="bonus" prop="bonus">
          <el-input v-model="form.bonus" placeholder="请输入bonus" />
        </el-form-item>
        <el-form-item label="expires_at" prop="expiresAt" label-width="100px">
          <el-date-picker clearable
                          v-model="form.expiresAt"
                          type="datetime"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="请选择expires_at"
                          disabled>
          </el-date-picker>
        </el-form-item>

        <el-form-item label="note" prop="note">
          <el-input v-model="form.note" type="textarea" placeholder="请输入内容" />
        </el-form-item>

        <!-- 添加到 el-form 中 -->
        <el-form-item label="Visibility" prop="visibility">
          <el-radio-group v-model="form.visibility" @change="handleVisibilityChange" disabled>
            <el-radio label="public">Public</el-radio>
            <el-radio label="private">Private</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- Private 模式下的用户和分组选择 -->
        <div v-if="form.visibility === 'private'">
          <!-- 分组选择 -->
          <el-form-item label="选择分组" prop="groupIds">
            <el-select
              v-model="form.groupIds"
              multiple
              placeholder="请选择分组"
              style="width: 100%"
              @change="handleGroupChange"
              disabled>
              <el-option
                v-for="group in groupList"
                :key="group.groupId"
                :label="group.groupName"
                :value="group.groupId">
              </el-option>
            </el-select>
          </el-form-item>

          <!-- 用户选择 -->
          <el-form-item label="选择用户" prop="userIds">
            <el-select
              v-model="form.userIds"
              multiple
              filterable
              remote
              reserve-keyword
              placeholder="请选择用户"
              :remote-method="searchUsers"
              :loading="userLoading"
              style="width: 100%"
              disabled>
              <el-option
                v-for="user in userList"
                :key="user.userId"
                :label="user.userName"
                :value="user.userId">
              </el-option>
            </el-select>
          </el-form-item>
        </div>

        <el-form-item label="notice" prop="notifyUsers">
          <el-checkbox
            v-model="form.notifyUsers"
            :disabled="form.visibility !== 'private' && form.visibility !== 'public'">
            Notify everyone who can see the offer
          </el-checkbox>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOffers, getOffers, updateOffers } from "@/api/purchase/offers"
import { listInventory } from "@/api/purchase/inventory"
import { listUser as listAllUsers } from "@/api/system/user"
import { listGroup } from "@/api/purchase/group"

export default {
  name: "ArchivedOffers",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // offers表格数据
      offersList: [],
      // inventory列表数据
      inventoryList: [],
      // 用户列表数据
      userList: [],
      // 用户加载状态
      userLoading: false,
      groupList: [],
      // 分组加载状态
      groupLoading: false,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // quantity总和
      quantityTotal: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        offerId: null,
        price: null,
        quantity: null,
        offerName: null,
        status: 'archived', // 只显示已归档的记录
        orderByColumn: '',  // 排序列
        isAsc: 'asc'        // 排序方式
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        productId: [
          { required: true, message: "product_id不能为空", trigger: "blur" }
        ],
        price: [
          { required: true, message: "price不能为空", trigger: "blur" }
        ],
        quantity: [
          { required: true, message: "quantity不能为空", trigger: "blur" }
        ],
        expiresAt: [
          { required: true, message: "expires_at不能为空", trigger: "blur" }
        ],
        visibility: [
          { required: true, message: "Visibility 不能为空", trigger: "change" }
        ],
      }
    }
  },
  watch: {
    'form.visibility': {
      handler(newVal) {
        if (newVal !== 'private' && newVal !== 'public') {
          this.form.notifyUsers = false;
        }
      }
    },
    // 监听 expiresAt 变化
    'form.expiresAt': {
      handler(newVal, oldVal) {
        // 当 expiresAt 变化且已选择商品时，重新生成 offer_name
        if (this.form.productId) {
          this.generateOfferName()
        }
      },
      immediate: false
    }
  },
  created() {
    this.getList()
    this.getInventoryList()
  },
  methods: {
    /** 验证私有模式下的选择 */
    validatePrivateSelection(rule, value, callback) {
      if (this.form.visibility === 'private') {
        // 检查是否选择了分组或用户
        const hasGroups = this.form.groupIds && this.form.groupIds.length > 0;
        const hasUsers = this.form.userIds && this.form.userIds.length > 0;

        if (!hasGroups && !hasUsers) {
          callback(new Error('Private 可见性下必须选择分组或用户'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    },
    /** 处理排序变化 */
    handleSortChange({ column, prop, order }) {
      // 如果是 price 列的排序
      if (prop === 'price' || prop === 'quantity') {
        // 清除其他排序条件
        this.queryParams.orderByColumn = prop;
        this.queryParams.isAsc = order === 'ascending' ? 'asc' : 'desc';
        // 重新获取数据
        this.getList();
      }
    },
    /** 查询inventory列表 */
    getInventoryList() {
      listInventory().then(response => {
        this.inventoryList = response.rows
      })
    },

    /** 查询分组列表 */
    getGroupList() {
      this.groupLoading = true;
      listGroup().then(response => {
        this.groupList = response.rows || response.data || [];
        this.groupLoading = false;
      }).catch(() => {
        this.groupLoading = false;
      });
    },
    /** 查询offers列表 */
    getList() {
      this.loading = true
      // 强制设置状态为 archived
      this.queryParams.status = 'archived'
      listOffers(this.queryParams).then(response => {
        this.offersList = response.rows
        this.total = response.total
        this.loading = false

        // 计算quantity总和
        this.quantityTotal = this.offersList.reduce((total, item) => {
          return total + (item.quantity ? parseFloat(item.quantity) : 0)
        }, 0)
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        offerId: null,
        productId: null,
        productName: null,
        price: null,
        quantity: null,
        bonus: null,
        expiresAt: null,
        note: null,
        offerName: null,
        visibility: "public",
        groupIds: [],         // 分组ID数组
        userIds: [],          // 用户ID数组
        notifyUsers: false,
        status: 'archived',   // 归档状态
        createdBy: null,
        createdAt: null,
        updatedAt: null,
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.offerId)
      this.single = selection.length !== 1
    },
    /** 处理 inventory 选择变化 */
    handleInventoryChange(val) {
      // 根据选择的商品ID查找对应的商品信息并生成 offer_name
      this.generateOfferName()
    },
    /** 处理 visibility 变化 */
    handleVisibilityChange(val) {
      if (val === 'private') {
        // 切换到 private 时加载分组和用户列表
        this.getGroupList()
        this.getUserList()
      } else {
        // 切换到其他模式时清空选择
        this.$set(this.form, 'groupIds', [])
        this.$set(this.form, 'userIds', [])
      }
      // 重置通知选项
      this.$set(this.form, 'notifyUsers', false)
    },
    /** 处理分组选择变化 */
    handleGroupChange(groupIds) {
      console.log("选择的分组:", groupIds)
      // 可以在这里根据选择的分组获取分组中的用户
      // this.getUsersByGroupIds(groupIds)
    },
    /** 获取用户列表 */
    getUserList() {
      this.userLoading = true;
      listAllUsers().then(response => {
        this.userList = response.rows || response.data || [];
        this.userLoading = false;
      }).catch(() => {
        this.userLoading = false;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const offerId = row.offerId || this.ids
      getOffers(offerId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改归档Offer"
        // 如果是 private 模式，加载分组和用户列表
        if (this.form.visibility === 'private') {
          this.getGroupList()
          this.getUserList()
        }
      })
    },
    /** 生成 offer_name */
    generateOfferName() {
      if (this.form.productId) {
        const selectedInventory = this.inventoryList.find(item => item.productId === this.form.productId)
        if (selectedInventory) {
          // 按照指定格式生成 offer_name:
          // 第一行: conditions
          // 第二行: name
          // 第三行: note
          // 第四行: expires_at
          let offerName = ''

          // 首先显示 conditions（如果存在）
          if (selectedInventory.conditions) {
            offerName += selectedInventory.conditions
          }

          // 换行后显示 name
          if (selectedInventory.name) {
            offerName += '-' + selectedInventory.name
          }

          // 换行后显示 note（如果存在）
          if (selectedInventory.note) {
            if (offerName) offerName += '\n'
            offerName += selectedInventory.note
          }

          // 换行后显示 expires_at（如果存在）
          if (this.form.expiresAt) {
            if (offerName) offerName += '\n'
            // 提取日期部分 (yyyy-MM-dd)
            const datePart = this.form.expiresAt.substring(0, 10)
            offerName += 'Expires: ' + datePart
          }

          // 设置生成的 offerName
          this.$set(this.form, 'offerName', offerName)
        }
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 在提交前确保生成 offer_name
          if (this.form.productId) {
            this.generateOfferName()
          }

          // 归档记录只能更新部分字段
          const updateData = {
            offerId: this.form.offerId,
            price: this.form.price,
            quantity: this.form.quantity,
            bonus: this.form.bonus,
            note: this.form.note,
            notifyUsers: this.form.notifyUsers,
            status: 'archived'
          }

          updateOffers(updateData).then(response => {
            this.$modal.msgSuccess("修改成功")
            this.open = false
            this.getList()
          }).catch(error => {
            console.error("修改失败:", error)
            this.$modal.msgError("修改失败: " + (error.message || "未知错误"))
          })
        }
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('purchase/offers/export', {
        ...this.queryParams,
        status: 'archived'
      }, `archived_offers_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
